
//
//  HLCollectViewController.m
//  HLAerospace
//
//  Created by hulian-ios on 17/9/15.
//  Copyright © 2017年 hulian-LB. All rights reserved.
//


#import "HLCollectViewController.h"
#import "HttpRequestManager.h"
#import <MJExtension/MJExtension.h>
#import <MJRefresh/MJRefresh.h>
#import "MBProgressHUD+HL.h"
#import "HLUserInfo.h"
#import "HLSeeMoreCell.h"
#import "HLCollect.h"
#import "HLCourseFoldViewController.h"
#import "HLCourseDetailViewController.h"
#import "HLArticleViewController.h"
#import "HLFoldCourse.h"

#define kPageLimit 10

@interface HLCollectViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSUInteger _currenPage;
}
@property (nonatomic ,strong) UITableView *tableView;
/** 数据源  */
@property (nonatomic ,strong) NSMutableArray *dataSource;

@end

@implementation HLCollectViewController

#pragma mark - Lazy

- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

#pragma mark - UI

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setUI];
    
    [self setupRefresh];
    
}

- (void)setUI
{
    self.navigationItem.title = @"我的收藏";
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = HLRGB(245, 245, 245);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.rowHeight = IS_IPHONE_5 ? 100 : 140;
    [_tableView registerClass:[HLSeeMoreCell class] forCellReuseIdentifier:@"HLSeeMoreCell"];
    [self.view addSubview:_tableView];
}

- (void)setupRefresh
{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewUsers)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreUsers)];
    
    [self.tableView.mj_header beginRefreshing];
    [self.tableView.mj_header setAutomaticallyChangeAlpha:YES];
    self.tableView.mj_footer.hidden = YES;
}


#pragma mark - Request

- (void)loadNewUsers
{
    [self cancerRequest];
    
    /**** 数据清空 ****/
    [self.dataSource removeAllObjects];
    
    _currenPage = 1;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"sign"] = [kHLRequestGetFavourate signStr];
    params[@"user_id"] = [HLUserInfo account].userid;
    params[@"page"] = @(_currenPage);
    params[@"limit"] = @(kPageLimit);
    __weak typeof(self) weakSelf = self;
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:kHLRequestGetFavourate parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject) {
        [weakSelf.tableView.mj_header endRefreshing];
        if ([responseObject[@"code"] integerValue] == 200) {
            _currenPage++;
            weakSelf.dataSource = [HLCollect mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [weakSelf.tableView reloadData];
            
            /**** 提示用户数据加载完毕 ****/
            weakSelf.tableView.mj_footer.hidden = NO;
            if (weakSelf.dataSource.count < kPageLimit) {
                _currenPage--;
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                /**** 重置底部状态 ****/
                [weakSelf.tableView.mj_footer endRefreshing];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        [weakSelf.tableView.mj_header endRefreshing];
        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];
    
}

- (void)loadMoreUsers
{
    [self cancerRequest];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"sign"] = [kHLRequestGetFavourate signStr];
    params[@"user_id"] = [HLUserInfo account].userid;
    params[@"page"] = @(_currenPage);
    params[@"limit"] = @(kPageLimit);
    __weak typeof(self) weakSelf = self;
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:kHLRequestGetFavourate parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject) {
        
        [weakSelf.tableView.mj_footer endRefreshing];
        if ([responseObject[@"code"] integerValue] == 200) {
            _currenPage++;
            NSMutableArray *tempArray = [NSMutableArray array];
            tempArray = [HLCollect mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [weakSelf.dataSource addObjectsFromArray:tempArray];
            [weakSelf.tableView reloadData];
            
            /**** 提示用户数据加载完毕 ****/
            if (tempArray.count < kPageLimit) {
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        [weakSelf.tableView.mj_footer endRefreshing];
        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];
    
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HLSeeMoreCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HLSeeMoreCell"];
    cell.fatherTitle.hidden = NO;
    cell.collect = self.dataSource[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HLCollect *course = self.dataSource[indexPath.row];
    HLFoldCourse *foldCourse = [HLFoldCourse new];
    foldCourse.wkid = course.course_id;
    if ([course.course_type isEqualToString:@"1"]) {
        HLCourseDetailViewController *couseDetail = [HLCourseDetailViewController new];
        couseDetail.history_record_pic_url = course.course_pic;
        couseDetail.foldCourse = foldCourse;
        [self.navigationController pushViewController:couseDetail animated:YES];
    }
    if ([course.course_type isEqualToString:@"2"]) {
        HLArticleViewController *article = [HLArticleViewController new];
        article.foldCourse = foldCourse;
        article.history_record_pic_url = course.course_pic;
        [self.navigationController pushViewController:article animated:YES];
    }
}

#pragma mark - Private

- (void)cancerRequest
{
    /**** 取消之前的请求 ****/
    [[HTTPRequestManager defaultManager].sessionManager.tasks makeObjectsPerformSelector:@selector(cancel)];
}

/***** 界面销毁 取消请求 ****/
- (void)dealloc
{
    [self cancerRequest];
}

@end

